import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/base/AbsLifecycleState.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/net/model/wishlis_model.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/app_const.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

class BenedictionPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _BenedictionState();
}

class _BenedictionState extends AbsLifecycleState<BenedictionPage>
    with
        TickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        AutoHideLoading {
  BenedictionViewModel vm = BenedictionViewModel();
  TextEditingController controller = TextEditingController();
  GlobalKey<RefreshIndicatorState> keyRefreshIndicatorState = GlobalKey();
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 0, vsync: this);
  }

  @override
  void onResume() {
    super.onResume();
    keyRefreshIndicatorState.currentState?.show();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Color(0xffF2F2F2),
      appBar: commonAppBar(
          AppLocalizationsWrapper.instance.unwrap(context).benediction,
          hideBack: true,
          actions: [
            CupertinoButton(
              padding: EdgeInsets.zero,
              onPressed: () {
                if (controller.text.isEmpty) {
                  Fluttertoast.showToast(
                      msg: AppLocalizationsWrapper.instance
                          .unwrap(context)
                          .benedictionContentTips);
                  return;
                }
                FocusManager.instance.primaryFocus?.unfocus();
                Future.value("").then((e) {
                  ARouter.instance.pagePush("/selectFrame", arguments: {
                    "source": SelectFrameSource.BENEDICTION,
                    "coverId": vm.selectedCoverId,
                    "content": controller.text,
                    "timingSwitch": vm.timingSwitch,
                    "sendDate": vm.selectedDateTime
                  });
                });
              },
              child: actionTextWidget(
                  AppLocalizationsWrapper.instance.unwrap(context).next),
            )
          ]),
      body: GestureDetector(
        onTap: () {
          FocusScopeNode currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus &&
              currentFocus.focusedChild != null) {
            FocusManager.instance.primaryFocus?.unfocus();
          }
        },
        child: SafeArea(
          child: ChangeNotifierProvider(
            create: (_) => vm,
            child: RefreshIndicator(
              color: Color(0xff3F74EF),
              key: keyRefreshIndicatorState,
              onRefresh: () {
                return vm.refresh(context).then((e) {
                  _tabController.dispose();
                  _tabController = TabController(
                      length: vm.tabsModel?.length ?? 0, vsync: this);
                });
              },
              child: SingleChildScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                child: Padding(
                  padding: const EdgeInsets.only(left: 15),
                  child: Column(
                    children: [
                      SizedBox(height: 12.5),
                      Padding(
                        padding: EdgeInsets.only(right: 15),
                        child: _previewWidget(),
                      ),
                      SizedBox(height: 18),
                      Padding(
                        padding: EdgeInsets.only(right: 15),
                        child: _benedictionInputWidget(),
                      ),
                      SizedBox(height: 18),
                      _tabListWidget(),
                      SizedBox(height: 15),
                      Padding(
                        padding: EdgeInsets.only(right: 15),
                        child: _timingWidget(),
                      ),
                      SizedBox(height: 10),
                      Padding(
                        padding: EdgeInsets.only(right: 15),
                        child: _timingTimeWidget(),
                      ),
                      SizedBox(height: 10),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {}

  @override
  bool get wantKeepAlive => true;

  _previewWidget() {
    return Selector<BenedictionViewModel, String>(
      builder: (BuildContext context, value, Widget? child) {
        return Stack(
          alignment: AlignmentDirectional.center,
          children: [
            AspectRatio(
                aspectRatio: 1.52, child: ColoredBox(color: Color(0xff484B52))),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 15),
              child: AspectRatio(
                aspectRatio: 1.58,
                child: ColoredBox(color: Color(0xffffffff)),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25),
              child: AspectRatio(
                aspectRatio: 1.59,
                child: ColoredBox(
                  color: Color(0xffB1B4BC),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 81, vertical: 56),
              child: AspectRatio(
                aspectRatio: 1.61,
                child: Image.network(value, fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                  return ColoredBox(color: Colors.grey);
                }),
              ),
            ),
          ],
        );
      },
      selector: (BuildContext, vm) {
        return vm.selectedCoverUrl ?? "";
      },
      shouldRebuild: (v1, v2) => v1 != v2,
    );
  }

  _benedictionInputWidget() {
    return Stack(alignment: AlignmentDirectional.bottomEnd, children: [
      Builder(builder: (context) {
        return TextField(
          controller: controller,
          maxLength: 100,
          minLines: 3,
          maxLines: 3,
          style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
          textInputAction: TextInputAction.done,
          onChanged: (value) {
            context.read<BenedictionViewModel>().setInputLength(value.length);
          },
          decoration: InputDecoration(
            counterText: '',
            hintText: AppLocalizationsWrapper.instance
                .unwrap(context)
                .benedictionHint,
            hintStyle: const TextStyle(color: Color(0xff999999), fontSize: 14),
            fillColor: Color(0xffffffff),
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 18, vertical: 13.5),
            filled: true,
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
              borderRadius: BorderRadius.circular(8.5),
            ),
          ),
        );
      }),
      Consumer<BenedictionViewModel>(
        builder: (BuildContext context, value, Widget? child) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 9.5, right: 12),
            child: Text(
              "${value.inputLength}/100",
              style: TextStyle(fontSize: 14, color: Color(0xff999999)),
            ),
          );
        },
      )
    ]);
  }

  _tabListWidget() {
    return Consumer<BenedictionViewModel>(
      builder: (BuildContext context, value, Widget? child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TabBar(
                controller: _tabController,
                tabAlignment: TabAlignment.start,
                isScrollable: true,
                overlayColor: WidgetStateProperty.all(Colors.transparent),
                dividerHeight: 0,
                labelStyle: TextStyle(
                    color: Color(0xff000000), fontWeight: FontWeight.bold),
                unselectedLabelStyle: TextStyle(
                    color: Color(0xff999999), fontWeight: FontWeight.normal),
                labelPadding: EdgeInsets.only(right: 31),
                indicatorColor: Colors.transparent,
                indicatorSize: TabBarIndicatorSize.label,
                tabs:
                    value.tabsModel?.map((e) => Text(e.name ?? "")).toList() ??
                        []),
            SizedBox(height: 11.5),
            Container(
              height: 90,
              child: TabBarView(
                  controller: _tabController,
                  children: value.tabsModel?.asMap().entries.map((e) {
                        var itemCount = e.value.items?.length ?? 0;
                        return LimitedBox(
                          child: ListView.separated(
                            scrollDirection: Axis.horizontal,
                            itemCount: itemCount,
                            itemBuilder: (context, index) {
                              var targetId = value.tabsModel?[e.key].items?[index].id;
                              return CupertinoButton(
                                padding: EdgeInsets.zero,
                                onPressed: () {
                                  vm.selected(e.key, index);
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(7),
                                    border: Border.all(
                                      color: targetId != null && value.selectedCoverId == targetId ? Color(0xff3F74EF) : Colors.transparent,
                                      width: 2.0,
                                    ),
                                  ),
                                  width: 145,
                                  height: 90,
                                  margin: EdgeInsets.only(
                                    right: index == (itemCount) - 1 ? 15 : 0,
                                  ),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(5),
                                    child: Image.network(
                                        e.value.items?[index].url ?? "",
                                        fit: BoxFit.cover, errorBuilder:
                                            (context, error, stackTrace) {
                                      return ColoredBox(color: Colors.grey);
                                    }),
                                  ),
                                ),
                              );
                            },
                            separatorBuilder:
                                (BuildContext context, int index) =>
                                    SizedBox(width: 18),
                          ),
                        );
                      }).toList() ??
                      []),
            )
          ],
        );
      },
    );
  }

  _timingWidget() {
    return Card(
      color: Colors.white,
      margin: EdgeInsets.zero,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Container(
        height: 60,
        padding: EdgeInsets.symmetric(horizontal: 18),
        child: Row(
          children: [
            Text(
              AppLocalizationsWrapper.instance.unwrap(context)!.scheduledSends,
              style: TextStyle(
                  color: Color(0xff333333),
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
            ),
            Expanded(
              flex: 1,
              child: Align(
                alignment: Alignment.centerRight,
                child: Transform.scale(
                  scale: 0.8,
                  child: Consumer<BenedictionViewModel>(
                    builder: (BuildContext context, vm, Widget? child) {
                      return CupertinoSwitch(
                        value: vm.timingSwitch,
                        activeColor: Color(0xff3F74EF),
                        onChanged: (bool value) {
                          vm.setTimingSwitch(value);
                        },
                      );
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _timingTimeWidget() {
    return Consumer<BenedictionViewModel>(
      builder:
          (BuildContext context, BenedictionViewModel value, Widget? child) {
        return Visibility(
          visible: value.timingSwitch,
          child: CupertinoButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              _showDateDialog(
                  value.selectedDateTime, value.minDateTime).then((e) {
                if (e != null) {
                  value.setSelectedDateTime(e);
                }
              });
            },
            child: Card(
              color: Colors.white,
              margin: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              child: Container(
                height: 60,
                padding: EdgeInsets.symmetric(horizontal: 18),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      AppLocalizationsWrapper.instance.unwrap(context).sendTime,
                      style: TextStyle(
                          color: Color(0xff333333),
                          fontSize: 14,
                          fontWeight: FontWeight.bold),
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          '${value.selectedDateTime.year.toString().padLeft(2, "0")}-${value.selectedDateTime.month.toString().padLeft(2, "0")}-${value.selectedDateTime.day.toString().padLeft(2, "0")} ${value.selectedDateTime.hour.toString().padLeft(2, "0")}:${value.selectedDateTime.minute.toString().padLeft(2, "0")}',
                          style:
                              TextStyle(color: Color(0xff999999), fontSize: 14),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 33),
                          child: Image.asset(
                            width: 10,
                            height: 20,
                            "images/icon_arrow_forward.png",
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Future<DateTime?> _showDateDialog(
      DateTime dateTime, DateTime minDateTime) async {
    final change = await showCupertinoModalPopup<bool>(
      context: context,
      builder: (BuildContext context) => Container(
        height: 260,
        color: CupertinoColors.systemBackground.resolveFrom(context),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    ARouter.instance.pagePop(arguments: false);
                  },
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                    child: Text(
                        AppLocalizationsWrapper.instance.unwrap(context).cancel,
                        style: TextStyle(color: Colors.grey, fontSize: 16)),
                  ),
                ),
                CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () async {
                    final duration = await _showTimeDialog(Duration(
                        hours: dateTime.hour, minutes: dateTime.minute));
                    if (duration != null) {
                      dateTime = dateTime.copyWith(
                          hour: duration.inHours,
                          minute: duration.inMinutes.remainder(60));
                    }
                    ARouter.instance.pagePop(arguments: duration != null);
                  },
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                    child: Text(
                        AppLocalizationsWrapper.instance.unwrap(context)!.next,
                        style:
                            TextStyle(color: Color(0xff3F74EF), fontSize: 16)),
                  ),
                )
              ],
            ),
            SizedBox(
              height: 216,
              child: CupertinoDatePicker(
                use24hFormat: true,
                mode: CupertinoDatePickerMode.date,
                dateOrder: DatePickerDateOrder.ymd,
                minimumDate: minDateTime,
                // minimumYear: dateTime.year,
                initialDateTime: dateTime,
                onDateTimeChanged: (DateTime value) {
                  dateTime = value;
                },
              ),
            ),
          ],
        ),
      ),
    );
    if (change == true) {
      return dateTime;
    }
    return null;
  }

  Future<Duration?> _showTimeDialog(Duration duration) async {
    final change = await showCupertinoModalPopup<bool>(
      context: context,
      builder: (BuildContext context) => Container(
        height: 260,
        color: CupertinoColors.systemBackground.resolveFrom(context),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    ARouter.instance.pagePop(arguments: false);
                  },
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                    child: Text(
                        AppLocalizationsWrapper.instance
                            .unwrap(context)!
                            .cancel,
                        style: TextStyle(color: Colors.grey, fontSize: 16)),
                  ),
                ),
                CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    ARouter.instance.pagePop(arguments: true);
                  },
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                    child: Text(
                        AppLocalizationsWrapper.instance
                            .unwrap(context)
                            .confirm,
                        style:
                            TextStyle(color: Color(0xff3F74EF), fontSize: 16)),
                  ),
                )
              ],
            ),
            SizedBox(
              height: 216,
              child: CupertinoTimerPicker(
                mode: CupertinoTimerPickerMode.hm,
                initialTimerDuration: duration,
                onTimerDurationChanged: (Duration value) {
                  duration = value;
                },
              ),
            ),
          ],
        ),
      ),
    );
    if (change == true) {
      return duration;
    }
    return null;
  }
}

class BenedictionViewModel extends ChangeNotifier {
  List<TabModel>? tabsModel;
  String? selectedCoverUrl;
  num? _selectedCoverId;

  num? get selectedCoverId => _selectedCoverId;

  bool _timingSwitch = false;

  bool get timingSwitch => _timingSwitch;
  int _inputLength = 0;

  int get inputLength => _inputLength;
  final DateTime minDateTime = DateTime.now();

  DateTime _selectedDateTime = DateTime.now();

  DateTime get selectedDateTime => _selectedDateTime;

  Future<void> refresh(BuildContext context) {
    return HttpManager.instance
        .doRequest("/api/wishlist", method: HttpMethod.POST)
        .then((e) {
      if (e.isSuccess) {
        tabsModel = (e.data['list'] as List<dynamic>?)
            ?.map((e) => TabModel.fromJson(e))
            .toList();
        if (tabsModel?.isNotEmpty == true &&
            tabsModel![0].items?.isNotEmpty == true) {
          final first = tabsModel![0].items![0];
          _selectedCoverId = first.id;
          selectedCoverUrl = first.url;
        }
        notifyListeners();
        return;
      }
      Fluttertoast.showToast(msg: e.msg ?? "");
    }).catchError((e) {
      print(e);
      Fluttertoast.showToast(
          msg: AppLocalizationsWrapper.instance.unwrap(context).netError);
    });
  }

  setTimingSwitch(bool timingSwitch) {
    _timingSwitch = timingSwitch;
    notifyListeners();
  }

  setInputLength(int inputLength) {
    _inputLength = inputLength;
    notifyListeners();
  }

  setSelectedDateTime(DateTime dateTime) {
    _selectedDateTime = dateTime;
    notifyListeners();
  }

  void selected(int key, int index) {
    final target = tabsModel![key].items![index];
    _selectedCoverId = target.id;
    selectedCoverUrl = target.url;
    notifyListeners();
  }
}
